package com.ext.demogateway.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import org.springframework.web.server.session.WebSessionIdResolver;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate template;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //下面是token的使用
        log.info("=========Come in MyLogGateWayFilter: " + new Date() + "==========");
        //String token = exchange.getRequest().getQueryParams().getFirst("token");
        String token = exchange.getRequest().getHeaders().getFirst("token");
        template.opsForValue().set("token", token);
        if (token == null) {
            log.info("==token为null，非法用户========");
            exchange.getResponse().setComplete();
        }
        // 成功
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("this is a post filter2");
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
